package io.renren.modules.police.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.police.dao.PoliceNewsDao;
import io.renren.modules.police.dto.PoliceNewsDTO;
import io.renren.modules.police.entity.PoliceNewsEntity;
import io.renren.modules.police.service.PoliceNewsService;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 新闻资讯信息表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2023-09-02
 */
@Service
public class PoliceNewsServiceImpl extends CrudServiceImpl<PoliceNewsDao, PoliceNewsEntity, PoliceNewsDTO> implements PoliceNewsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public QueryWrapper<PoliceNewsEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String keyWord = (String)params.get("keyWord");

        QueryWrapper<PoliceNewsEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        if (StringUtils.isNotBlank(keyWord)) {
            wrapper.and(wp -> wp.like("title", keyWord).or().like("content", keyWord));
        }

        return wrapper;
    }


    @Override
    public PageData<PoliceNewsDTO> getPage(Map<String, Object> params) {
        PageData<PoliceNewsDTO> page = this.page(params);
        page.getList().forEach(e -> {
            SysUserDTO creatorDTO = sysUserService.get(e.getCreator());
            e.setCreatorName(creatorDTO.getRealName());
            SysUserDTO updaterDTO = sysUserService.get(e.getUpdater());
            e.setUpdaterName(updaterDTO.getRealName());
        });
        return page;
    }

    @Override
    public List<PoliceNewsDTO> getAllNews(Map<String, Object> params) {
        List<PoliceNewsEntity> entityList = this.baseDao.selectList(null);
        List<PoliceNewsDTO> dtoList = ConvertUtils.sourceToTarget(entityList, PoliceNewsDTO.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dtoList.forEach(e -> {
            SysUserDTO creatorDTO = sysUserService.get(e.getCreator());
            e.setCreatorName(creatorDTO.getRealName());
            SysUserDTO updaterDTO = sysUserService.get(e.getUpdater());
            e.setUpdaterName(updaterDTO.getRealName());
            e.setCreateTime(simpleDateFormat.format(e.getCreateDate()));
        });
        return dtoList;
    }
}